pacman::p_load(tidyverse,xtable)

setwd("")#set working directory 

voter <- read.csv("VOTER Panel Data Files/voter_panel.csv")

# table A15----- 
voter['demprimary16_2016'][voter['demprimary16_2016'] == 1] <- "Clinton '16"
voter['demprimary16_2016'][voter['demprimary16_2016'] == 2] <- "Sanders '16"
voter['demprimary16_2016'][voter['demprimary16_2016'] == 3] <- "Other '16"
voter['demprimary16_2016'][voter['demprimary16_2016'] == 4] <- NA_character_
voter['demprimary16_2016'][voter['demprimary16_2016'] == "4"] <- NA_character_
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 1] <- "Warren '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 2] <- "Biden '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 3] <- "Sanders '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 4] <- "Buttigieg '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 5] <- "Klobuchar '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 6] <- "Bloomberg '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 7] <- "Other '20"
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 8] <- NA_character_
voter['demprimary20post_2020Sep'][voter['demprimary20post_2020Sep'] == 99] <- NA_character_

demprimary.16.20 <- voter %>%
  dplyr::select(demprimary16_2016, demprimary20post_2020Sep) %>%
  na.omit(.)  %>%
  group_by(demprimary16_2016, demprimary20post_2020Sep) %>%
  dplyr::summarise(count = n())  %>%
  pivot_wider(names_from = demprimary20post_2020Sep, values_from = count, values_fill = 0)
colnames(demprimary.16.20)
sum(rowSums(demprimary.16.20[,2:8]))
sum(demprimary.16.20[,2:8])#1324 

demprimary.16.20.short <- cbind(demprimary.16.20$demprimary16_2016, 100*(demprimary.16.20[,2:8] / sum(rowSums(demprimary.16.20[,2:8]))))
demprimary.16.20.short[,2:ncol(demprimary.16.20.short)]<-round(demprimary.16.20.short[,2:ncol(demprimary.16.20.short)])
colnames(demprimary.16.20.short)[1]<-""
demprimary.16.20.short
print(xtable(demprimary.16.20.short,
             digits=0, 
             file="t:voter-dems-1620", 
             caption=c("Preferences of The Democracy Fund Voter Study Group respondents who reported voting in the Democratic primaries in 2016 and 2020. Values represent percentages of all respondents. N=1324.")),
      include.rownames=F,
      scalebox=0.85,
      file="tableA15.tex")#table A15

